<!--  -->
<template>
  <li :class="classes" @mouseenter="handleMouseenter" @mouseleave="handleMouseleave" @focus=this.handleMouseenter>
    <div :class="submenuTitleClasses" ref="reference"  @click.stop="handleClick">
      <slot name="title"></slot>
      <Icon v-if="isShowIcon" type="icon-down" class="sh-menu-submenu-title-icon"></Icon>
    </div>
    <collapse-transition v-if="mode === 'ver' && isCollape === false">
      <ul :class="[prefixCls]" v-show="opened"><slot></slot></ul>
    </collapse-transition>
    <transition v-else>
      <div ref="menu"
      v-show="opened && isHovered"
      >
        <ul :class="popupClasses">
          <slot></slot>
        </ul>
      </div>
    </transition>
  </li>
</template>

<script>
import Icon from '../../icon'
import { findComponentUpward, findComponentsDownward, findComponentDownward } from '../../../utils/assist'
import Emitter from '../../../mixins/emitter'
import mixin from './MenuAssistant'
import CollapseTransition from '../../../utils/transitions/collapse-transition'
import Popper from '../../../utils/vue-popper'

const poperMixins = {
  props: {
    transformOrigin: {
      type: [Boolean, String],
      default: false
    },
    offset: Popper.props.offset,
    boundariesPadding: Popper.props.boundariesPadding,
    popperOptions: Popper.props.popperOptions
  },
  data: Popper.data,
  methods: Popper.methods,
  beforeDestroy: Popper.beforeDestroy,
  deactivated: Popper.deactivated
}
const prefixCls = 'sh-menu'

export default {
// import引入的组件需要注入到对象中才能使用
  name: 'Submenu',
  mixins: [ Emitter, mixin, poperMixins ],
  components: { Icon, CollapseTransition },
  props: {
    name: {
      type: [String, Number],
      required: true
    },
    disabled: {
      type: Boolean,
      default: false
    },
    showTimeout: {
      type: Number,
      default: 300
    },
    hideTimeout: {
      type: Number,
      default: 300
    }
  },
  data () {
    // 这里存放数据
    return {
      prefixCls: 'sh-menu',
      popperJS: null,
      active: false,
      opened: false,
      childrenActive: false,
      isHovered: false
    }
  },
  // 监听属性 类似于data概念
  computed: {
    classes () {
      return [
        {
          [`${prefixCls}-submenu`]: this.isShowMenuActive,
          [`${prefixCls}-submenu-sub`]: !this.isShowMenuActive,
          [`${prefixCls}-item-active`]: this.active && this.isShowMenuActive,
          [`${prefixCls}-opened`]: this.opened,
          [`${prefixCls}-submenu-disabled`]: this.disabled,
          [`${prefixCls}-submenu-has-parent-submenu`]: !this.isShowMenuActive,
          [`${prefixCls}-child-item-active`]: this.active
        }
      ]
    },
    popupClasses () {
      return [
        `${prefixCls}-submenu-popup`,
        {
          [`${prefixCls}-submenu-popup-${this.currentPlacement}`]: true
        }
      ]
    },
    submenuTitleClasses () {
      return [{
        [`${prefixCls}-submenu-title`]: this.isShowMenuActive,
        [`${prefixCls}-submenu-sub-title`]: !this.isShowMenuActive,
        [`${prefixCls}-submenu-title-first`]: !this.isShowIcon,
        [`${prefixCls}-submenu-title-second`]: this.isShowIcon,
        [`${prefixCls}-submenu-title-open`]: this.isShowIcon && this.childrenActive,
        [`${prefixCls}-submenu-title-chidren-active`]: this.childrenActive
      }]
    },
    accordion () {
      return this.menu.accordion
    },
    isFirstLevel () {
      let isFirstLevel = true
      // 禁止submenu上面套group,或者上面套menu
      let parent = findComponentUpward(this, 'Submenu')
      let parentMenu = findComponentUpward(this, 'Menu')
      if (parent && parentMenu) {
        isFirstLevel = false
      }
      return isFirstLevel
    },
    isShowMenuActive () {
      // 展示
      let isFirstLevel = true
      // 禁止submenu上面套group,或者上面套menu
      let parent = findComponentUpward(this, 'Submenu')
      let parentGroup = findComponentUpward(this, 'MenuGroup ')
      let parentMenu = findComponentUpward(this, 'Menu')
      if (parent && parentMenu) {
        isFirstLevel = false
      } else if (parentGroup && parentMenu) {
        isFirstLevel = false
      }
      if (isFirstLevel) {
        return true
      } else if (!isFirstLevel && !this.isMenuPopup) {
        return true
      } else {
        return false
      }
    },
    isShowIcon () {
      let isFirstLevel = true
      let isShowIcon = true
      // 禁止submenu上面套group,或者上面套menu
      let parent = findComponentUpward(this, 'Submenu')
      let parentMenu = findComponentUpward(this, 'Menu')
      if (parent && parentMenu) {
        isFirstLevel = false
      }
      if ((this.mode === 'ver' || this.mode === 'ver-show') && isFirstLevel) {
        isShowIcon = false
      }
      return isShowIcon
    }
  },
  // 监控data中的数据变化
  watch: {
    isHovered () {
      // console.log('==================')
      // console.log(this.isHovered)
      // console.log('==================')
    },
    opened (val) {
      if (this.isMenuPopup) {
        this.$nextTick(_ => {
          this.updatePopper()
        })
      }
    },
    isCollape (val) {
      this.$parent.$children.forEach(item => {
        if (item.$options.name === 'Submenu') item.opened = false
      })
      this.$nextTick(() => {
        this.initPopper()
        this.createPopper()
      })
    }
  },
  // 方法集合
  methods: {
    handleMouseenter () {
      if ((this.expands === 'hover' && !this.disabled) || this.mode === 'hor') {
        clearTimeout(this.timeout)
        this.menu.updateOpenKeys(this.name)
        this.opened = true
        this.isHovered = true
      }
    },
    handleMouseleave () {
      if ((this.expands === 'hover' && !this.disabled) || this.mode === 'hor') {
        this.menu.updateOpenKeys(this.name)
        this.opened = false
        this.isHovered = false
      }
    },
    handleClick () {
      if (this.disabled) return
      if (this.mode === 'hor') return
      const opened = this.opened
      if (this.accordion) {
        this.$parent.$children.forEach(item => {
          if (item.$options.name === 'Submenu') item.opened = false
        })
      }
      this.opened = !opened
      this.menu.updateOpenKeys(this.name)
    },
    updatePlacement () {
      this.currentPlacement = this.mode === 'hor' && this.isFirstLevel
        ? 'bottom-start'
        : 'right-start'
    },
    initPopper () {
      this.referenceElm = this.$el
      this.popperElm = this.$refs.menu
      this.updatePlacement()
    },
    handleCollapseToggle (value) {
    }
  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted () {
    this.menu.addSubmenu(this)
    this.initPopper()
    this.$on('on-menu-item-select', (name) => {
      if (this.mode === 'hor' || this.isCollape) this.opened = false
      this.dispatch('Menu', 'on-menu-item-select', name)
      return true
    })
    this.$on('on-update-active-name', (updateDict) => {
      if (findComponentUpward(this, 'Submenu')) this.dispatch('Submenu', 'on-update-active-name', updateDict)
      if (findComponentsDownward(this, 'Submenu')) {
        findComponentsDownward(this, 'Submenu').forEach(item => {
          item.active = false
        })
      }
      this.active = updateDict.status
    })
    this.$on('on-update-active-children', (updataDict) => {
      if (updataDict.name) {
        let active = false
        if (findComponentsDownward(this, 'MenuItem')) {
          findComponentsDownward(this, 'MenuItem').forEach(item => {
            if (item.name === updataDict.name) {
              active = true
            }
          })
        }
        this.childrenActive = active
      }
      if (findComponentDownward(this, 'Submenu')) this.broadcast('Submenu', 'on-update-active-children', updataDict)
    })
    this.$on('toggle-collapse', this.handleCollapseToggle)
  },
  beforeDestroy () {
    this.menu.removeSubmenu(this)
  }
}
</script>
